#引入相关模块
from simple import MQTTClient
import network,time,dht,json
from machine import I2C,Pin,Timer,ADC
from ssd1306 import SSD1306_I2C

WIFI_LED=Pin(2, Pin.OUT) #初始化WIFI指示灯
wlan = network.WLAN(network.STA_IF) #STA模式

#初始化相关模块
i2c = I2C(sda=Pin(13), scl=Pin(14))
oled = SSD1306_I2C(128, 64, i2c, addr=0x3c)


#创建DTH11对象
d = dht.DHT11(Pin(27)) #传感器连接到引脚15
time.sleep(1)   #首次启动停顿1秒让传感器稳定

#初始化ADC,Pin=36，11DB衰减，测量电压0-3.3V
Light = ADC(Pin(36))
Light.atten(ADC.ATTN_11DB)

#初始化ADC,Pin是32，开启11DB衰减，量程增至0-3.3V
Soil = ADC(Pin(32))
Soil.atten(ADC.ATTN_11DB)

#OLED屏幕显示，没有屏幕可以把这个注释掉
def Oled_show():
    
    d.measure()         #温湿度采集
    oled.fill(0) #清屏背景黑色
    oled.text('Power:   '+str(WIFI_LED.value()),0,0)
    oled.text('Soil:  '+str(Soil.read()),0,18)
    oled.text('Light:   '+str(Light.read()),0,28)
    oled.text('tem:     '+str(d.temperature() )+' C',0,38)   #温度显示
    oled.text('hum:     '+str(d.humidity())+' %',0,48)  #湿度显示
    oled.show()   

#WIFI连接函数
def WIFI_Connect():
    wlan.active(True)                   #激活接口
    start_time=time.time()              #记录时间做超时判断

    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('123', '12345678') #输入WIFI账号密码

        while not wlan.isconnected():

            #LED闪烁提示
            WIFI_LED.value(1)
            time.sleep_ms(300)
            WIFI_LED.value(0)
            time.sleep_ms(300)

            #超时判断,15秒没连接成功判定为超时
            if time.time()-start_time > 15 :
                print('WIFI Connected Timeout!')
                break

    if wlan.isconnected():
        #串口打印信息
        print('network information:', wlan.ifconfig())
        return True
    else:
        return False

def MQTT_Send(tim):
    Oled_show()     #OLED屏幕显示
    mymessage = {"id":"123", "version":"1.0",
                 "params":{"Temp":{"value":d.temperature()},      #温度
                 "switchlight":{"value":bool(WIFI_LED.value())},  #WiFi灯的亮灭状态
                 "humidity":{"value":d.humidity()},               #湿度
                 "soil":{"value":Soil.read()},                    #土壤湿度
                 "light":{"value":Light.read()}}}                 #光照
#     print(mymessage)                                            #用于测试数据是否接收正常
    msg_json = json.dumps(mymessage)
    client.publish(topic=publish_Topic, msg=msg_json)
    client.check_msg()
                 
def MQTT_callback(topic, msg):
    #post/reply主题上报数据
    if (str(topic) == "b'$sys/4QBhkhln6H/DeviceLZY27240926/thing/property/post/reply'"):
        json_str = msg.decode('utf-8')
        dic_msg = json.loads(json_str)
        #如果上报数据成功，会pass掉成功信息
        if(dic_msg["msg"] == 'success'):
            pass
        #失败会报出错在哪里
        else:
            print("topic:{}".format(topic))
            print("msg:{}".format(msg))
    #设置开关，通过set主题下发属性
    else:
        print("topic:{}".format(topic))
        print("msg:{}".format(msg))
        json_str = msg.decode('utf-8')
        dic_msg = json.loads(json_str)
        id = dic_msg ['id']
        #字典类型
        res_msg_dic={"id": id,  "code": 200,   "msg": "I have received successly!"}
        #json类型
        res_msg_json = json.dumps(res_msg_dic)
        client.publish(topic=respose_Topic, msg=res_msg_json, retain=False, qos=0)
        if dic_msg["params"]["switchlight"]:
            WIFI_LED.value(1)
        else:
            WIFI_LED.value(0)
        
if WIFI_Connect():
    #订阅主题
    publish_Topic='$sys/4QBhkhln6H/DeviceLZY27240926/thing/property/post'
    post_Topic='$sys/4QBhkhln6H/DeviceLZY27240926/thing/property/post/reply'
    subscribe_Topic='$sys/4QBhkhln6H/DeviceLZY27240926/thing/property/set'
    respose_Topic = '$sys/4QBhkhln6H/DeviceLZY27240926/thing/property/set_reply'
    # 客户端ID
    CLIENT_ID = 'DeviceLZY27240926'
    # user_name名称
    user_name = '4QBhkhln6H'
    user_password = 'version=2018-10-31&res=products%2F4QBhkhln6H%2Fdevices%2FDeviceLZY27240926&et=1800000000&method=md5&sign=Mw6yI2B92Ufo1YW3bRLP8Q%3D%3D'
    SERVER = 'mqtts.heclouds.com'
    PORT = 1883
    client = MQTTClient(CLIENT_ID, SERVER, 0, user_name, user_password, 60)
    print('start connect!')#开始连接云平台
    client.set_callback(MQTT_callback)
    client.connect()
    print('success connect!')#连接成功
    client.subscribe(post_Topic)
    client.subscribe(subscribe_Topic)
#开启RTOS定时器，编号为-1
tim = Timer(-1)
tim.init(period=2000, mode=Timer.PERIODIC,callback=MQTT_Send) #周期为2000ms
